import express from "express";
import { addComments, addLike, findCommentsByLinkId } from "../model/comment.js";
import { updateStars } from "../model/links.js";
import { ChangeComment } from "../utils/index.js";

const commentRouter = express.Router()





//添加评论
/**
 *data:{
 *   content:STRING
 *   starts:INT  
 * }
 */
commentRouter.post('/add', async (req, res) => {
    const data = req.body;
    const userId = req.cookies.userId;
    ChangeComment(data)

    //评论
    const result = await addComments({ ...data, userId: Number(userId) })

    //查找全部星级:
    const comments = await findCommentsByLinkId(Number(data.linkId))

    let starts = 0;
    comments.forEach((comment) => {
        starts += comment.starts
    })
    starts /= comments.length
    //范围1-5整数
    starts = Math.ceil(starts) + 1 >= 5 ? 5 : Math.ceil(starts) + 1

    //写回数据库
    await updateStars(Number(data.linkId), starts)

    res.send({
        msg: 'ok',
        data: result
    })
})


JSON.stringify()

commentRouter.post('/like', async (req, res) => {
    //获取被点赞的评论id
    const { id } = req.body

    const result = await addLike(Number(id))
    res.send({
        msg: 'ok',
        data: result
    })
})

export default commentRouter
